"use client";
import "./index.css";
import {
  Button,
  Card,
  Progress,
  Radio,
  Space,
  Typography,
  message,
  Skeleton,
} from "antd";
import {
  listMultiQuestionByPageUsingPost,
  MultiQuestionRecordsUsingPost,
  MultiQuestionRemarkUsingPost,
} from "@/api/mutliQuestionController";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useSelector } from "react-redux";
import { RootState } from "@/stores";

const { Title, Text } = Typography;

export default function ExamBankPage({
  params,
}: {
  params: { questionBankId: number };
}) {
  const router = useRouter();
  const { questionBankId } = params;
  const [questions, setQuestions] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedAnswers, setSelectedAnswers] = useState<
    Record<string, string>
  >({});
  const [submitted, setSubmitted] = useState(false);
  const [score, setScore] = useState(0);

  const [TotalScores, setTotalScores] = useState(0);
  const [timeElapsed, setTimeElapsed] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalQuestions, setTotalQuestions] = useState(0);
  const loginUser = useSelector((state: RootState) => state.loginUser);

  // 检查登录状态
  useEffect(() => {
    if (!loginUser) {
      message.error("请先登录");
      router.push("/login");
    }
  }, [router, loginUser]);

  // 计时器效果
  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (!submitted) {
      timer = setInterval(() => setTimeElapsed((prev) => prev + 1), 1000);
    }
    return () => clearInterval(timer);
  }, [submitted]);

  // 加载题目
  const loadQuestions = async (page: number = 1) => {
    try {
      setLoading(true);
      const res = await listMultiQuestionByPageUsingPost({
        questionBankId: questionBankId,
        current: currentPage,
        pageSize: 5,
      });
      if (res.data) {
        // @ts-ignore
        setQuestions(res.data.records || []);
        // @ts-ignore
        setTotalQuestions(res.data.total || 0);
        // @ts-ignore
        setCurrentPage(res.data.current);
        setSelectedAnswers({});
        setSubmitted(false);
        setTimeElapsed(0);
      }
    } catch (e: any) {
      message.error("获取题目失败: " + e.message);
      if (e.response?.status === 401) router.push("/login");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (loginUser) loadQuestions();
  }, [questionBankId, loginUser]);

  // 处理答案选择
  const handleAnswerSelect = (questionId: string, answer: string) => {
    setSelectedAnswers((prev) => ({ ...prev, [questionId]: answer }));
  };

  // 提交答案
  const handleSubmit = async () => {
    try {
      let correctCount = 0;
      const multiQuestionIds: number[] = [];
      const wrongQuestionIds: number[] = [];
      let totalScore = 0;
      let rightScore = 0;
      questions.forEach((q) => {
        console.log(q);
        const questionId = q.id;
        multiQuestionIds.push(questionId);
        totalScore += Number(q.score);
        if (selectedAnswers[q.id] === q.rightAnswer) {
          correctCount++;
          rightScore += Number(q.score);
        } else {
          wrongQuestionIds.push(questionId);
        }
      });
      console.log(totalScore, rightScore);
      // const totalScore = questions.reduce((sum, q) => sum + q.score, 0);
      // const userScore = Math.round(
      //   (correctCount / questions.length) * totalScore,
      // );

      await MultiQuestionRecordsUsingPost({
        questionBankId: questionBankId,
        multiQuestionIds,
        wrongQuestionIds,
      });

      setTotalScores(totalScore);
      setScore(rightScore);
      setSubmitted(true);
      message.success(`得分: ${rightScore}/${totalScore}`);
    } catch (e: any) {
      message.error("提交记录失败: " + e.message);
    }
  };

  // 继续刷题 - 修复后的版本
  const handleContinue = () => {
    const nextPage = currentPage + 1;
    setCurrentPage(nextPage);
    loadQuestions(nextPage);
  };

  // 重新开始
  const handleRestart = async () => {
    try {
      await MultiQuestionRemarkUsingPost({
        questionBankId: questionBankId,
      });
      message.success("已重置做题记录");
      loadQuestions(1);
    } catch (e: any) {
      message.error("重置失败: " + e.message);
    }
  };

  // 返回首页
  const handleReturnHome = () => {
    router.push("/");
  };

  // 格式化时间显示
  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
  };

  // 计算答题进度
  const progressPercent = Math.round(
    (Object.keys(selectedAnswers).length / questions.length) * 100,
  );

  if (loading) {
    return (
      <div className="exam-container">
        <Card className="exam-card">
          <Skeleton active paragraph={{ rows: 8 }} />
        </Card>
      </div>
    );
  }

  if (questions.length === 0) {
    return (
      <div className="exam-container">
        <Card className="exam-card" style={{ textAlign: "center" }}>
          <p style={{ marginBottom: 24 }}>暂无更多题目</p>
          <div style={{ display: "flex", justifyContent: "center", gap: 16 }}>
            <Button type="primary" onClick={handleReturnHome}>
              返回首页
            </Button>
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div className="exam-container">
      <Card className="exam-card">
        <div className="exam-header">
          <Title level={3}>{questions[0]?.subject || "科目"} - 在线测试</Title>
          <div className="exam-meta">
            <Text strong>用时: {formatTime(timeElapsed)}</Text>
            {submitted && (
              <div>
                <Text strong type="success" style={{ marginRight: 5 }}>
                  得分: {score}
                </Text>
                -
                <Text type="warning" strong style={{ marginLeft: 5 }}>
                  总分为：{TotalScores}
                </Text>
              </div>
            )}
            <Text>
              题目组数: {currentPage}/{Math.ceil(totalQuestions / 5)}
            </Text>
          </div>
        </div>

        <div className="progress-container">
          <Progress
            percent={progressPercent}
            status="active"
            strokeColor={{ from: "#108ee9", to: "#87d068" }}
          />
          <div className="progress-stats">
            <Text>已答: {Object.keys(selectedAnswers).length}</Text>
            <Text>
              未答: {questions.length - Object.keys(selectedAnswers).length}
            </Text>
          </div>
        </div>

        <div className="questions-list">
          {questions.map((question, index) => (
            <Card key={question.id} className="question-card">
              <Title level={4} className="question-title">
                {index + 1}. {question.question}
              </Title>

              <Radio.Group
                onChange={(e) =>
                  handleAnswerSelect(question.id, e.target.value)
                }
                value={selectedAnswers[question.id]}
                disabled={submitted}
                className="options-group"
              >
                <Space direction="vertical" style={{ width: "100%" }}>
                  {["A", "B", "C", "D"].map((option) => {
                    const answerText = question[`answer${option}`];
                    return (
                      answerText && (
                        <Radio
                          key={option}
                          value={option}
                          className={`option-radio ${
                            submitted && option === question.rightAnswer
                              ? "correct-option"
                              : ""
                          } ${
                            submitted &&
                            selectedAnswers[question.id] === option &&
                            option !== question.rightAnswer
                              ? "wrong-option"
                              : ""
                          }`}
                        >
                          {option}. {answerText}
                        </Radio>
                      )
                    );
                  })}
                </Space>
              </Radio.Group>

              {submitted && (
                <div className="answer-feedback">
                  <Text
                    type={
                      selectedAnswers[question.id] === question.rightAnswer
                        ? "success"
                        : "danger"
                    }
                  >
                    {selectedAnswers[question.id] === question.rightAnswer
                      ? "✓ 正确"
                      : `✗ 错误 (正确答案: ${question.rightAnswer})`}
                  </Text>
                  {question.analysis && (
                    <div className="analysis-text">
                      解析: {question.analysis}
                    </div>
                  )}
                </div>
              )}
            </Card>
          ))}
        </div>

        <div className="action-buttons">
          {!submitted ? (
            <Button
              type="primary"
              size="large"
              onClick={handleSubmit}
              disabled={
                Object.keys(selectedAnswers).length !== questions.length
              }
            >
              提交答案
            </Button>
          ) : (
            <div className="continue-section">
              <Button type="primary" onClick={handleContinue}>
                继续刷题
              </Button>
              <Button onClick={handleRestart} style={{ marginLeft: 16 }}>
                重新开始
              </Button>
            </div>
          )}
        </div>
      </Card>
    </div>
  );
}
